const XLSX = require('xlsx');
var questionNum = 100;
var questions;
var errs = [];
var curQuestionIndex = -1;
var examTimer = null;
var beginTime;
var finishTime;
var curTime;
var jsonData = null;
window.onload = function () {
    document.addEventListener('keydown', function (event) {
        if (event.key === 'Enter' || event.keyCode === 13) {
            document.getElementById('confirm').click();
        }
    });
    document.getElementById('confirm').onclick = function () {
        this.disabled = true;
        setTimeout(() => this.disabled = false, 100);
        var rst = checkCurWordAnswer();
        var tip = ''
        if (rst) {
            tip = '😀'
        } else {
            tip = '🐷'
        }
        document.getElementById('rstTip').innerText = tip;
        setTimeout(() => {
            document.getElementById('rstTip').innerText = '';
        }, 500);
        curQuestionIndex++;
        showWordsCurExam();
        showErrWordsList();
        countRealTimeRstAndShow();

        document.getElementById('ying').select();
        document.getElementById('ying').focus();
        if (curQuestionIndex == questionNum) {
            document.getElementById('finish').click();
        }

    }
    document.getElementById('finish').onclick = function () {
        document.getElementById('rstTime').innerText = Math.floor(new Date() - beginTime) / 1000 + '秒';
        questions = 0;
        curQuestionIndex = -1;
        if (examTimer != null) {
            clearInterval(examTimer);
        }
        this.disabled = true;
        document.getElementById('confirm').disabled = true;
    }
    document.getElementById('exportErrBtn').onclick = function () {
        if (!errs || errs.length == 0) {
            return;
        }
        const worksheet = XLSX.utils.json_to_sheet(errs);
        // 创建一个新的工作簿并将工作表添加进去
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
        // 导出 Excel 文件
        XLSX.writeFile(workbook, 'errs-' + new Date().getTime() + '.xlsx');
    }
    document.getElementById('selectTerm').onchange = function () {
        showChapter(this.value);
    }
    document.getElementById('btnReMake').onclick = function () {
        makeQuestionByChapter();
        startTheTimer();
        showWordsCurExam();
    };
}

document.getElementById('fileInput').addEventListener('change', function (event) {
    if (event.target.files.length === 0) {
        console.log('文件选择被取消');
        // 在这里处理取消上传的逻辑
    } else {
        console.log('文件已选择:', event.target.files[0]);
        document.getElementById('output').innerText = "数据加载中";
        // 在这里处理文件上传的逻辑
        const file = event.target.files[0];
        const reader = new FileReader();
        reader.onload = function (e) {
            const data = new Uint8Array(e.target.result);
            const workbook = XLSX.read(data, { type: 'array' });

            // 处理workbook，例如显示第一个sheet的内容
            let chooseIndex = 0;
            if (document.getElementById('phrase').checked
                && workbook.SheetNames.length > 1) {
                chooseIndex = 1;
            }
            const firstSheetName = workbook.SheetNames[chooseIndex];
            const worksheet = workbook.Sheets[firstSheetName];
            jsonData = XLSX.utils.sheet_to_json(worksheet);
            //console.log(jsonData);
            document.getElementById('output').innerText = "数据加载完成";
            document.getElementById('content').hidden = false;
            document.getElementById('fileInput').disabled = true;
            //document.getElementById('output').innerText = JSON.stringify(jsonData, null, 2);
            //document.getElementById('output').innerText = JSON.stringify(questions, null, 2);
            makeQuestionRandom();
            showTirms();
            startTheTimer();
            showWordsCurExam();


        };
        reader.readAsArrayBuffer(file);
    }
});
function showTirms() {
    document.getElementById('selectTerm').innerHTML = "";
    if (jsonData == null || !Array.isArray(jsonData) || jsonData.length <= 0) {
        return;
    }
    var setTirms = new Set();
    var i = 0;
    for (i = 0; i < jsonData.length; i++) {
        setTirms.add(jsonData[i]["学期"]);
    }
    var arrTirms = Array.from(setTirms);
    for (i = 0; i < arrTirms.length; i++) {
        var option = document.createElement('option');
        option.text = arrTirms[i];
        document.getElementById('selectTerm').appendChild(option);
    }
    showChapter(document.getElementById('selectTerm').value);
}
function showChapter(v) {
    document.getElementById('divChaptersArea').innerHTML = "";
    var setChapter = new Set();
    var i = 0;
    for (i = 0; i < jsonData.length; i++) {
        if (jsonData[i]["学期"] == v) {
            setChapter.add(jsonData[i]["单元"])
        }
    }
    var arrChapter = Array.from(setChapter);
    for (i = 0; i < arrChapter.length; i++) {
        var label = document.createElement('label');
        label.innerText = arrChapter[i];
        document.getElementById('divChaptersArea').appendChild(label);

        var input = document.createElement('input');
        input.type = 'checkbox';
        input.value = arrChapter[i];
        input.name = 'chapterChooseGroup'
        input.checked = true;
        document.getElementById('divChaptersArea').appendChild(input);

    }
}
function startTheTimer() {
    if (examTimer != null) {
        clearInterval(examTimer);
    }
    beginTime = new Date();
    examTimer = setInterval(() => {
        document.getElementById('time').value = Math.floor(new Date() - beginTime) / 1000 + '秒';
    }, 1000);
}
function makeQuestionRandom() {
    if (jsonData == null || !Array.isArray(jsonData) || jsonData.length <= 0) {
        return;
    }

    questions = new Array();
    if (jsonData.length < questionNum) {
        questionNum = jsonData.length;
    }
    curQuestionIndex = 0;
    var i = 0;
    var random1 = 0;
    for (i = 0; i < questionNum; i++) {
        random1 = Math.floor(Math.random() * jsonData.length);
        jsonData[random1]['right'] = -1;
        questions.push(jsonData[random1]);
    }
}
function makeQuestionByChapter() {
    if (jsonData == null || !Array.isArray(jsonData) || jsonData.length <= 0) {
        return;
    }
    var checkboxes = document.getElementsByName("chapterChooseGroup");
    var selectedValues = [];
    for (var i = 0; i < checkboxes.length; i++) {
        if (checkboxes[i].checked) {
            selectedValues.push(checkboxes[i].value);
        }
    }
    console.log(selectedValues);
    var strTirm = document.getElementById('selectTerm').value;

    questions = new Array();
    questionNum = jsonData.length;
    curQuestionIndex = 0;
    var i = 0;
    for (i = 0; i < jsonData.length; i++) {
        var item = jsonData[i];
        if (item["学期"] === strTirm && selectedValues.indexOf(item["单元"]+'')>-1) {
            item['right'] = -1;
            questions.push(item);
            
        }
        console.log( item["单元"]+'') ;
    }
    console.log(questions);
}
function showWordsCurExam() {
    if (questions.length > curQuestionIndex) {
        document.getElementById('no').value = curQuestionIndex + 1 + ' / ' + questions.length;
        document.getElementById('han').value = questions[curQuestionIndex]['含义'];
    }else{
        document.getElementById('no').value = "";
        document.getElementById('han').value = "";
    }
}
function checkCurWordAnswer() {
    var answer = document.getElementById('ying').value
    var rst = true;
    if (answer.trimEnd() === questions[curQuestionIndex]['英文'].trimEnd()) {
        questions[curQuestionIndex]['right'] = 1;
        rst = true;
    } else {
        questions[curQuestionIndex]['right'] = 0;
        errs.unshift(questions[curQuestionIndex]);
        rst = false;
    }
    return rst;
}
function showErrWordsList() {

    document.getElementById('errList').innerText = JSON.stringify(errs, null, 2);

}
function countRealTimeRstAndShow() {
    var rightNum = 0;
    var wrongNum = 0;
    var rate = 0;
    for (var i = 0; i < questions.length; i++) {
        if (questions[i].right == 1) {
            rightNum++;
        }
        if (questions[i].right == 0) {
            wrongNum++;
        }
    }
    if (questions.length > 0) {
        rate = rightNum / questions.length * 100;
    }
    document.getElementById('rstRight').innerHTML = rightNum;
    document.getElementById('rstWrong').innerHTML = wrongNum;
    document.getElementById('rstRate').innerHTML = rate + '%';

}